package com.ease.web.xwt.component;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.ClassUtils;

import com.ease.web.xwt.core.XComponentTemplateFactory;

import freemarker.template.Template;

/**
 * 
 * @author nathanleewei
 * 
 */
public abstract class XAbstractComponent implements XComponent {

	/**
	 *
	 */
	private static final long serialVersionUID = 4636040399937848886L;

	private static final transient Log log = LogFactory.getLog(XAbstractComponent.class);

	// default attribute
	public static String WIDTH = "160";

	public static int HEIGHT = 24;

	public static String NAME = "xwt";

	//
	protected String name;

	protected String value;

	protected String width;

	protected String title;

	public XAbstractComponent() {
		this.setWidth(WIDTH);
	}

	protected abstract String getTemplate();

	public String generate() {
		if (null == name) {
			this.name = "";
		}

		String templateFullyName = ClassUtils.classPackageAsResourcePath(XComponent.class) + '/' + this.getTemplate();
		Template template = XComponentTemplateFactory.getInstance().getComponentTemplate(templateFullyName);
		StringWriter writer = new StringWriter();
		if (null != template) {
			try {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("x", this);
				template.process(map, writer);
			} catch (Exception e) {
				log.error("template process exception: templateFullyName=" + templateFullyName, e);
			}
		}

		return writer.toString();
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public String getWidth() {
		return width;
	}

	public void setWidth(String width) {
		this.width = width;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

}